package co.bugu.es8.infra.repo;

import co.bugu.es8.infra.entity.User;
import co.elastic.clients.elasticsearch._types.query_dsl.QueryBuilders;
import co.elastic.clients.elasticsearch._types.query_dsl.RangeQuery;
import co.elastic.clients.json.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author daocers
 * @date 2025/4/27 18:31
 */
@Service
public class UserTemplateRepo {
//    @Autowired
    public ElasticsearchRestTemplate template;


    public boolean save(User user) {
        User save = template.save(user);
        return true;
    }


    public boolean saveUser(List<User> users) {
        template.save(users);
        return true;
    }

    public User findById(Long id) {
        User user = template.get(id + "", User.class);
        return user;
    }

    public List<User> search() {
        RangeQuery query = QueryBuilders.range().field("age").gt(JsonData.of(28)).build();

        SearchHits<User> res = template.search(CriteriaQuery.builder(Criteria.where("age").greaterThan("28")).build(), User.class);
        List<SearchHit<User>> searchHits = res.getSearchHits();
        if (CollectionUtils.isEmpty(searchHits)) {
            return new ArrayList<>();
        } else {
            List<User> list = searchHits.stream().map(item -> item.getContent()).collect(Collectors.toList());
            return list;
        }
    }
}
